// server.js
const http = require('http');

let clients = [];
let currentVersion = '20250720-001';

// 创建 HTTP 服务
const server = http.createServer((req, res) => {
    if (req.url === '/events') {
        // 设置 SSE 响应头
        res.writeHead(200, {
            'Content-Type': 'text/event-stream', // 必须的
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*',
        });

        // 初次推送当前版本
        res.write(`data: ${JSON.stringify({ version: currentVersion })}\n\n`);
        clients.push(res);
        // 客户端断开连接时移除
        req.on('close', () => {
            clients = clients.filter(c => c !== res);
        })
    } else if (req.url === '/notify' && req.method === 'POST') {
        let body = '';
        req.on('data', chunk => body += chunk);
        req.on('end', () => {
            const { version } = JSON.parse(body);
            currentVersion = version;

            // 推送新版本给所有连接的客户端
            clients.forEach(client => {
                client.write(`data: ${JSON.stringify({ version })}\n\n`);
            });

            res.writeHead(200);
            res.end('OK');
        })
    } else {
        res.writeHead(404);
        res.end('Not Found');
    }
})

server.listen(3000, () => {
    console.log('SSE server running at http://localhost:3000');
});